<?php

namespace App\Http\Controllers\House;

use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\Common\CommonParam;
use App\Models\Config;
use App\Models\Hourse\Hourse;
use App\Models\House\House;
use App\Models\House\HouseAttributeValue;
use App\Models\House\HouseFllowupRecord;
use App\Models\House\HouseImg;
use App\Models\House\Landlord;
use App\Models\User\SystemUser;
use App\Service\UserService;
use EasyWeChat\Factory;
use function foo\func;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

/**
 * @group 房屋api
 */
class HouseController extends Controller
{

    /**
     * search 房源搜索
     * @time:2020/4/23-12:37
     *
     * @param Request $request
     * @author:dongdong
     * @queryParam example_id required The id of the location.
     * @bodyParam example_id required The id of the location.
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function search(Request $request)
    {

        $search = $request->get('search');
        $JsonSearch = json_decode($search, true);
        $input = $JsonSearch['input']??0;
        $selltype = $JsonSearch['selltype']??2;
        $sort = $JsonSearch['sort']??0;

        $data = House::query()
            ->when($input,function($query, $input){
                 return $query->orWhereHas('landlord',function($query) use ($input){
                     $query->where('phone', $input);
                 })
                     ->orWhere('village','like',"%{$input}%")
                     ->orWhere('detail_address','like',"%{$input}%")
                     ->orWhere('internal_structure','like',"%{$input}%")
                     ->orWhere('price','like',"%{$input}%")
                     ->orWhere('remark','like',"%{$input}%");
            })
            ->when($selltype,function($query, $selltype){
                return $query->where('selltype', $selltype);
            })
            ->with([
                'HouseImg'  => function($query){
                    return $query->select(['id','house_id','file'])->groupBy('house_id');
                },
                'User' => function($query) {
                    $query->select(['nickname','id']);
                }
            ])
            ->when($sort,function($query, $sort){
                foreach ($sort as $k=>$v) {
                    if ($v['field'] !== 'more') {
                        $query->orderBy($v['field'], $v['sort']);
                    }
                }
            })
            ->orderBy('id','asc')
            ->orderBy('status','asc')
            ->paginate()
            ->toArray();
            $house =  new House();
            foreach($data['data'] as $key=>&$val){
                $val['attr'] = $house->getValues($val['id']);
            }
        return returnData($data);
    }

    /**
     * info 房源信息
     * @time:2020/4/27-17:41
     * \
     * @param Request $request
     * @author:dongdong
     * @queryParam example_id required The id of the location.
     * @bodyParam example_id required The id of the location.
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function info(Request $request)
    {
        $request->validate(['house_id'=>'required|exists:houses,id']);
        $house_id = $request->get('house_id',0);

        $data = House::query()
            ->with([
                'HouseImg'  => function($query){
                    return $query->select(['id','house_id','file']);
                },
                'User' => function($query) {
                    $query->select(['nickname','id']);
                },
                'landlord' => function($query) {
                    $query->select(['name','id','phone']);
                },
//                'FllowupRecord' => function($query) {
//                    $query->orderBy('id','desc');
//                },
            ])
            ->where('id',$house_id)
            ->orderBy('created_at','desc')
            ->orderBy('status','asc')
            ->first();
        $data['attr'] = $data->getValues($data->id);
        $data['fllowup_record'] = HouseFllowupRecord::query()->where('house_id', $house_id)->with([
            'user' => function($query){
                $query->select(['id','username','phone']);
            }
        ])->orderBy('id','desc')->get();
        return returnData($data);
    }

    /**
     * addHouse 添加房屋
     * @time:2020/4/30-12:45
     *
     * @param Request $request
     * @author:dongdong
     * @queryParam example_id required The id of the location.
     * @bodyParam example_id required The id of the location.
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function addHouse(Request $request)
    {
        $requestData = $request->all();//([

DB::beginTransaction();
        #  房屋信息
        $price = $request->get('price', 0 );
        $internal_structureId =$request->get('internal_structure','');
        if ($internal_structureId) {
            $param = CommonParam::query()->find($internal_structureId);
        }
        $sellType = $request->get('selltype',2);
        $price_unit = $request->get('price_unit','');
        if ($sellType !=3&&!$price_unit) {
            $price_unit = '万';
        }
        $houseData = [
            'price' => $price,
            'price_unit' => $price_unit,
            'remark' => $request->get('remark',''),
            'village' => $request->get('village'),
            'size' => $request->get('size',0),
            'selltype' => $sellType,
            'total_floors' => $request->get('total_floors',0),
            'detail_address' => $request->get('detail_address',''),
            'area' => $request->get('area'),
            'internal_structure' => $param->name,
            'user_id' => Auth::id(),
        ];
        $house = new House($houseData);
        $house->save();

        # 房东信息
        $landlordData = $request->get('landlord');
        # 房东
        if ($phone = $landlordData['phone'] )   {
            $landlordsaveData = [
                'name' =>  $landlordData['name'] ,
                'phone' => $landlordData['phone'],
            ];
            $landlord =  Landlord::query()->firstOrCreate(['phone'=>$landlordData['phone']],$landlordsaveData);

            $house->landlord_id = $landlord->id;
        }

        $house->save();
        # 房屋属性
         $atrr = (new House())->getAllAttr();
         $attrValArr = [];
         foreach ($atrr as $atr){
             foreach ($requestData as $key=> $reval){

                 if ($key == $atr['field']) {
                     $attrValArr[] = [
                        'attribute_param_id' => $atr['id'],
                         'value_param_id' => $reval,
                         'house_id' => $house->id,
                         'created_at' => date("Y-m-d H:i:s"),
                         'updated_at' => date("Y-m-d H:i:s")
                     ];
                 }
             }
         }
         HouseAttributeValue::query()->insert($attrValArr);
        DB::commit();
        return returnData($house);
    }

    /**\
     * getHouseAttr 获取房屋属性
     * @time:2020/4/30-16:48
     *
     * @author:dongdong
     * @queryParam example_id required The id of the location.
     * @bodyParam example_id required The id of the location.
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function getHouseAttr()
    {
        $attr = (new House())->getAllAttr();
        $paramsIds = $attr->pluck('id');

        $data = CommonParam::query()
            ->whereIn('id', $paramsIds)
            ->with(
                [
                    'childParam' => function($query){
                        $query->select(['id','parent_id','name']);
                    },
                ])
            ->select([
                'id','parent_id','name','field'
            ])
            ->get()
            ->toArray();

        return returnData($data);
    }

    /**
     * addFile 添加文件
     * @time:2020/5/10-1:18
     *
     * @author:dongdong
     * @queryParam example_id required The id of the location.
     * @bodyParam example_id required The id of the location.
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function addFile(Request $request)
    {
        $request->validate([
            'house_id' => 'required',
            'url' => 'required',
        ]);

        $house = HouseImg::query()->create([
            'house_id' => $request->get('house_id'),
            'file' => $request->get('url')
        ]);
//        $house->file = urloss($house->file, ['x-oss-process'=>'style/abridge']);
        return returnData($house);
    }

    /**
     * deleteFile 删除文件
     * @time:2020/5/10-1:18
     *
     * @author:dongdong
     * @queryParam example_id required The id of the location.
     * @bodyParam example_id required The id of the location.
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function deleteFile(Request $request)
    {
        $request->validate([
            'house_id' => 'required',
            'file' => 'required',
        ]);
        $file = $request->get('file');
        $filePath='';
        if (strpos($file,'?')!=false) {
            $filearr = explode('?', $file);
            Log::info('$filearr', [$filearr]);
            $url = $filearr[0];
            if (strpos($url,'http://')!==false) {
                $url = str_replace('http://','', $url);
            }
            Log::info('$url', [$url]);
            $index= strpos($url,'/');
            Log::info('$index', [$index]);
            if ($index!=false) {
                $filePath = substr($url,$index+1 );
            }
        }
        Log::info('$filePath', [$filePath]);
        $house = HouseImg::query()->where([
            'house_id' => $request->get('house_id'),
            'file' => $filePath
        ])->first();

        if (!$house) {
            throw new ApiException('该房屋无此数据');
        }
        if ($house->delete()) {
            return returnData($house,'删除成功');
        }
        throw new ApiException('删除失败');
    }

    /**
     * addFllowup 添加 跟进记录
     * @time:2020/5/10-1:47
     *
     * @author:dongdong
     * @queryParam example_id required The id of the location.
     * @bodyParam example_id required The id of the location.
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function addFllowup(Request $request)
    {
        $data = $request->validate([
            'house_id' => 'required',
            'content' => 'required',
        ]);
        $data['user_id'] = \auth()->id();
        $record = HouseFllowupRecord::query()->create($data);
        return returnData($record);
    }

    /**
     * edit  编辑
     * @time:2020/5/11-15:52
     *
     * @param Request $request
     * @author:dongdong
     * @queryParam example_id required The id of the location.
     * @bodyParam example_id required The id of the location.
     * @response {
     * "data": {
     * },
     * "status_code": 200,
     * "message" : "success"
     * }
     */
    public function edit(Request $request)
    {
        $requestData = $request->all();//([
        $internal_structureId =$request->get('internal_structure','');
        if ($internal_structureId) {
            $param = CommonParam::query()->find($internal_structureId);
        }
        DB::beginTransaction();
        #  房屋信息
        $price = $request->get('price', 0 );
        $houseData = [
            'status' => $request->get('status',1),
            'price' => $price,
            'price_unit' => $request->get('price_unit',''),
            'remark' => $request->get('remark',''),
            'village' => $request->get('village'),
            'size' => $request->get('size',0),
            'selltype' => $request->get('selltype',2),
            'total_floors' => $request->get('total_floors',0),
            'detail_address' => $request->get('detail_address',''),
            'area' => $request->get('area'),
            'internal_structure' => $param->name,
//            'user_id' => Auth::id(),
        ];
        $house_id=  $request->get('house_id',0);
        $house = House::query()->find($house_id);
        $house->update($houseData);

        # 房东信息
        $landlordData = $request->get('landlord');
        # 房东
        if ($phone = $landlordData['phone'] )   {
            $landlordsaveData = [
                'name' =>  $landlordData['name'] ,
                'phone' => $landlordData['phone'],
            ];
            $landlord =  Landlord::query()->firstOrCreate(['phone'=>$landlordData['phone']],$landlordsaveData);

            $house->landlord_id = $landlord->id;
        }

        $house->save();
        # 房屋属性
        $atrr = (new House())->getAllAttr();
        $attrValArr = [];
        foreach ($atrr as $atr){
            foreach ($requestData as $key=> $reval){
                if ($key == $atr['field']) {
                    $attrValArr[] = [
                        'attribute_param_id' => $atr['id'],
                        'value_param_id' => $reval,
                        'house_id' => $house->id,
                        'created_at' => date("Y-m-d H:i:s"),
                        'updated_at' => date("Y-m-d H:i:s")
                    ];
                }
            }
        }
        HouseAttributeValue::query()->where('house_id', $house_id)->delete();
        HouseAttributeValue::query()->insert($attrValArr);
        DB::commit();
        return returnData($house);
    }
}
